<template>
    <div class="user-list">
        <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片内容-->
        <el-card>
            <!--搜索框+添加按钮-->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="clearQuery" @keyup.enter.native="searchUsers">
                        <el-button slot="append" icon="el-icon-search" @click="searchUsers"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="3">
                    <el-button type="primary" @click="handleShowAddDialog">添加用户</el-button>
                </el-col>
            </el-row>

            <!--用户列表区域-->
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope" width="40px">
                        <!--{{scope.row}} -->
                        <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope" width="170px">
                        <!--删除-->
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger"  size="mini" icon="el-icon-delete" 
                                @click="DelUser(scope.row)"></el-button>
                        </el-tooltip>
                        
                        <!--修改-->
                        <el-tooltip  effect="dark" content="修改信息" placement="top" :enterable="false">
                            <el-button type="success" size="mini" icon="el-icon-setting" 
                                @click="handleShowEditDialog(scope.row)"></el-button>
                        </el-tooltip>
                        
                        <!--分配权限-->
                        <el-tooltip  effect="dark" content="分配权限" placement="top" :enterable="false">
                            <el-button type="warning" size="mini" icon="el-icon-star-off" 
                                @click="handleShowSetRoleDialog(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!--分页区域-->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[2,5,10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!--添加/编辑  用户对话框-->
        <el-dialog
            :title="isAddUser?`添加用户`:`编辑用户`"
            :visible.sync="showdialogVisible"
            width="50%"
            @close="closeAddUserDialog">
            <!--内容主体区-->
            <el-form :model="addUserFrom" :rules="addUserRules" ref="UserDialogFromRef" label-width="70px">
                <el-form-item label="用户名" prop="username" >
                    <el-input v-model="addUserFrom.username" :disabled="!isAddUser"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="isAddUser">
                    <el-input v-model="addUserFrom.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserFrom.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUserFrom.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!--底部按钮区-->
            <span slot="footer">
                <el-button @click="closeAddUserDialog">取 消</el-button>
                <el-button type="primary" @click="handleDialogPost">确 定</el-button>
            </span>
        </el-dialog>

        <!--分配角色-->
        <el-dialog
            title="分配角色"
            :visible.sync="showSetRoleDialog"
            width="50%"
            @close="closeRoleDialog">
            <!--内容主体区-->
            <div>
                <p>当前用户：{{currentUser.username}}</p>
                <p>当前用户角色: {{currentUser.role_name}}</p>
                <p>
                    分配当前角色：
                    <el-select v-model="selectedRoleId" placeholder="请选择角色">
                        <el-option
                            v-for="item in rolesList "
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            
            <!--底部按钮区-->
            <span slot="footer">
                <el-button @click="closeRoleDialog">取 消</el-button>
                <el-button type="primary" @click="handleSetRole">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
//方法
import {getUsers,changeUserState,handleAddUser,getUserById,handleEditUser,deleteUserById,setUserRole} from '@/request/users'
import {getRoles} from '@/request/roles'
export default {
    components: {

    },
    data() {
        //验证邮箱规则
        const checkEmail = (rules,value,callback)=>{
            //校验邮箱的正则
            var regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            if(regEmail.test(value)){
               return callback()
            }else{
               return callback(new Error('请输入正确邮箱'));
            }
        }
        //验证手机号规则
        const checkMobile = (rules,value,callback)=>{
            //校验邮箱的正则
            var regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
            if(regMobile.test(value)){
               return callback()
            }else{
               return callback(new Error('请输入正确手机号'));
            }
        }
        return {
            //获取用户列表参数对象
            queryInfo:{
                query: '',
                pagenum: 1,
                pagesize: 10
            },
            userList:[],
            total:0,
            showdialogVisible:false,
            isAddUser:false,
            addUserFrom:{   //添加用户表单数据
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addUserRules:{  //添加用户验证规则
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 5, max: 10, message: '密码在 5 到 10 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur'}
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur'}
                ]
            },
            showSetRoleDialog: false,
            currentUser: {},    //需要被分配的用户
            rolesList:[],
            selectedRoleId:''
        }
    },
    computed: {

    },
    created() {
        this.loadUserData(this.queryInfo)
    },
    mounted() {

    },
    methods: {
        //关闭设置角色对话框
        closeRoleDialog(){
            this.showSetRoleDialog = false
        },
        //打开设置角色对话框
        handleShowSetRoleDialog(user){
            this.currentUser = user

            //显示前获取全部可选角色
            getRoles()
            .then(res=>{
                if(res.meta.status!==200){
                    this.$message.error(res.meta.msg)
                }else{
                    this.rolesList = res.data  
                }
            })

            this.showSetRoleDialog = true
        },
        //确认选择角色
        handleSetRole(){
            if(!this.selectedRoleId){
                return this.$message.error('请选择用户角色')
            }
            setUserRole(this.currentUser.id,{rid:this.selectedRoleId})
            .then(res=>{
                if(res.meta.status!==200){
                    this.$message.error(res.meta.msg)
                }else{
                    this.$message.success(res.meta.msg)
                    this.showSetRoleDialog = false
                    this.loadUserData(this.queryInfo)
                }
            })
        },
        /*
            加载用户列表
        */
        loadUserData(params){
            getUsers(params)
            .then(res=>{
                if(res.meta.status!==200){
                    return this.$message.error('获取用户列表失败')
                }else{
                    this.userList = res.data.users
                    this.total = res.data.total
                }
            })
        },
        /*
            监听pageSize改变
        */
        handleSizeChange(newSize){
            this.queryInfo.pagesize = newSize
            this.loadUserData(this.queryInfo)
        },
        /*
            监听页码值page改变
        */
        handleCurrentChange(newPage){
            this.queryInfo.pagenum = newPage
            this.loadUserData(this.queryInfo)
        },
        /*
            swutch开关的改变
        */
       async changeUserState(userinfo){
           let res = await changeUserState(userinfo.id,userinfo.mg_state)
           if(res.meta.status!=200){
               userinfo.mg_state = !userinfo.mg_state
               this.$message.error('用户状态更新失败')
           }else{
               this.$message.success('用户状态更新成功！')
           }
       },
       /*
            查询用户
        */
       searchUsers(){
           this.loadUserData(this.queryInfo)
       },
       /*
            清空搜索框内容时事件
        */
       clearQuery(){
           this.queryInfo.query = ''
           this.loadUserData(this.queryInfo)
       },
       /*
            展示添加用户信息对话框
       */
       handleShowAddDialog(){
           this.showdialogVisible = true
           this.isAddUser = true
           this.initAdduserFrom()
       },
       /*
            展示编辑用户信息对话框
      */
       handleShowEditDialog(userinfo){
           getUserById(userinfo.id)
           .then(res=>{
               if(res.meta.status===200){
                   this.addUserFrom = res.data
                   this.showdialogVisible = true
                   this.isAddUser = false
               }else{
                   this.$message.error('获取用户信息失败！')
               }
           })
       },
       handleDialogPost(){
           this.isAddUser? this.AddUser() : this.EditUser()
       },
       /*
            用户信息初始化
       */
       initAdduserFrom(){
           this.addUserFrom = {   
                username:'',
                password:'',
                email:'',
                mobile:''
            }
       },
       /*
            关闭添加用户弹窗事件
       */
       closeAddUserDialog(){
           this.showdialogVisible = false
           this.isAddUser = false
           this.initAdduserFrom()
           this.$refs.UserDialogFromRef.resetFields()
       },
       /*
            点击确定 -->  添加用户
       */
        AddUser(){
            this.$refs.UserDialogFromRef.validate(async valid=>{
              if(valid){  //校验通过
                handleAddUser(this.addUserFrom)
                .then(res=>{
                    if(res.meta.status!=201){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.closeAddUserDialog() //关闭对话框并清除校验
                        this.loadUserData(this.queryInfo)  //刷新数据
                        this.$message.success('添加用户成功！')
                    }
                })
                .catch(err=>{
                    this.$message.error(err)
                })
                
              }else{
                  this.$message.error('请完善用户信息！')
              }
            })
        },
        EditUser(){
            this.$refs.UserDialogFromRef.validate(async valid=>{
              if(valid){  //校验通过
                handleEditUser(this.addUserFrom.id,this.addUserFrom)
                .then(res=>{
                    if(res.meta.status!==200){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.closeAddUserDialog() //关闭对话框并清除校验
                        this.loadUserData(this.queryInfo)  //刷新数据
                        this.$message.success(res.meta.msg)
                    }
                })
                .catch(err=>{
                    this.$message.error(err)
                })
                
              }else{
                  this.$message.error('请完善用户信息！')
              }
            })
        },
        async DelUser(userInfo){
            let delResult = await this.$confirm(`确定删除${userInfo.username}用户吗?`,'提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            .catch(err=>err)
            // 取消是cancel  确定是confirm
            if(delResult==='confirm'){
                deleteUserById(userInfo.id)
                .then(res=>{
                    if(res.meta.status!==200){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.$message.success(res.meta.msg)
                        this.loadUserData(this.queryInfo)  //刷新数据
                    }
                })
            }
        }    
    }
}
</script>

<style lang='less' scoped>
.user-list{
    padding: 20px;
}
.el-card{
    width: 1200px;
}
.el-table{
    margin-top: 20px;
    font-size: 14px;
}
</style>
